from django.db.models.signals import post_save, post_delete
from django.dispatch import receiver
from django.contrib.auth.models import User
from django.apps import apps
from .user_profile import UserProfile
from core.utils import log_operation
from core.middleware.request_context import get_current_user, get_current_ip

@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
    if created:
        UserProfile.objects.create(user=instance)

@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
    instance.profile.save()

from core.middleware.request_context import get_current_user, get_current_ip

# 通用日志信号处理函数
def _log_model_operation(sender, instance, operation_type, **kwargs):
    # 排除日志模型本身，避免递归
    if sender.__name__ == 'OperationLog':
        return

    # 获取当前请求用户
    user = get_current_user()
    if not user or not user.is_authenticated:
        return

    # 获取IP地址
    ip_address = get_current_ip()

    # 获取对象信息
    content_type = sender.__name__
    object_id = instance.id
    object_name = str(instance)

    # 记录日志
    log_operation(
        user=user,
        operation_type=operation_type,
        content_type=content_type,
        object_id=object_id,
        object_name=object_name,
        details=f'{content_type} {operation_type} operation',
        ip_address=ip_address
    )

@receiver(post_save)
def log_model_save(sender, instance, created, **kwargs):
    operation_type = 'create' if created else 'update'
    _log_model_operation(sender, instance, operation_type, **kwargs)

@receiver(post_delete)
def log_model_delete(sender, instance, **kwargs):
    _log_model_operation(sender, instance, 'delete', **kwargs)

# 自动为所有模型注册信号
def register_all_models_signals():
    for model in apps.get_models():
        # 跳过OperationLog模型
        if model.__name__ == 'OperationLog':
            continue
        post_save.connect(log_model_save, sender=model)
        post_delete.connect(log_model_delete, sender=model)

# 注册信号
register_all_models_signals()
